//
//  SPHomeViewController.m
//  Sport
//
//  Created by Cass on 2017/11/1.
//  Copyright © 2017年 Cass. All rights reserved.
//

#import "SPHomeViewController.h"
#import "UIBarButtonItem+SPExtension.h"
#import "SPAddFriendsViewController.h"
#import "SPStateCell.h"
#import "SPHomeStateModel.h"
#import "SPStateViewController.h"
#import "SPCityViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "SPUserInfoController.h"
#import "SPradarController.h"
@interface SPHomeViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate,SPCityViewControllerDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) CLGeocoder *geocoder;
@property (copy, nonatomic) NSString *selectdCity;
@property (copy, nonatomic) NSString *locationCity;
@property (strong, nonatomic) NSTimer *timer;
@property (strong, nonatomic) NSMutableArray<SPHomeStateModel *> *states;
@property(nonatomic, strong) NSArray<SPHomeStateModel *> *curStates;

@property(nonatomic, strong)UIBarButtonItem *radarItem;

@end

@implementation SPHomeViewController


-(UIBarButtonItem *)radarItem{
    if (_radarItem == nil) {
        _radarItem = [[UIBarButtonItem alloc]initWithTitle:@"发现" style:UIBarButtonItemStyleDone target:self action:@selector(goToRadar)];
    }
    return _radarItem;
}

-(void)goToRadar{
    NSLog(@"leida");
    SPradarController *radar = [[UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]]instantiateViewControllerWithIdentifier:@"SPradarController"];
    [self.navigationController pushViewController:radar animated:YES];
}

- (CLGeocoder *)geocoder{
    if (!_geocoder) {
        _geocoder = [[CLGeocoder alloc]init];
    }
    return _geocoder;
}
- (NSMutableArray<SPHomeStateModel *> *)states{
    if (!_states) {
        _states = [[NSMutableArray alloc]init];
    }
    return _states;
}
- (NSArray<SPHomeStateModel *> *)curStates{
    if (!_curStates) {
        _curStates = [[NSArray alloc]init];
    }
    return _curStates;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self radarItem];
//    [self.navigationItem setRightBarButtonItem:_radarItem];
//    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.scrollView.delegate = self;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.pagingEnabled = YES;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.tableView.mj_header beginRefreshing];
    
    [self setBasic];
}

- (void)setBasic{
    self.navigationItem.title = @"首页";
    UIBarButtonItem *barLeftItem = [UIBarButtonItem itemWithImage:@"btn_xuanze_1" selectedImage:@"" title:@"定位中" target:self action:@selector(leftItemTapped:)];
    [barLeftItem setTintColor:[UIColor yellowColor]];
    self.navigationItem.leftBarButtonItem = barLeftItem;
//    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"tab_icon_jia" selectedImage:@"tab_icon_jia" title:@"" target:self action:@selector(rightItemTapped:)];
    
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.scrollView.mas_centerX);
        make.bottom.mas_equalTo(self.scrollView).with.offset(0);
    }];
    
    [self setScrollImg];
    [self addTimer];
    
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //手动设置权限进行系统适配
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    //开始定位，不断调用其代理方法
    [self.locationManager startUpdatingLocation];
    
}

- (void)loadNewData{
    NSString *url = [NSString stringWithFormat:@"http://39.108.132.194/Sport/returnSubmitInfo.php"];
    
    [SPHttpClient POST:url parameters:nil success:^(id responseObject) {
        NSArray *info = responseObject;
//        NSLog(@"%@",info);
        NSMutableArray *arr = [NSMutableArray array];
        for (NSDictionary *dict in info) {
            SPHomeStateModel *state = [SPHomeStateModel mj_objectWithKeyValues:dict];
            [arr addObject:state];
        }
        self.states  = arr;
        if (_states.count >= 7) {
            self.curStates = [_states subarrayWithRange:NSMakeRange(0, 7)];
        }
        else{
            NSInteger t = _states.count;
            self.curStates = [_states subarrayWithRange:NSMakeRange(0, t)];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        nil;
    }];
}

- (void)loadMoreData{
//    if (self.tableView.mj_footer.state == MJRefreshStateNoMoreData) {
////         [self.tableView.mj_footer endRefreshing];
//
//    }else{
        self.curStates = [NSArray arrayWithArray:self.states];
        [self.tableView reloadData];
        NSLog(@"上拉刷新");
        [self.tableView.mj_footer endRefreshing];

//    }
    
}
- (void)leftItemTapped:(UIBarButtonItem *)item{
    SPCityViewController *cityVC = [[UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:NSStringFromClass([SPCityViewController class])];
    cityVC.title = @"切换城市";
    cityVC.delegate = self;
    [self.navigationController pushViewController:cityVC animated:YES];
    
}

- (void)rightItemTapped:(UIBarButtonItem *)ietm{
    SPAddFriendsViewController *addVC = [[UIStoryboard storyboardWithName:@"Message" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:NSStringFromClass([SPAddFriendsViewController class])];
    [self.navigationController pushViewController:addVC animated:YES];
}
- (void)setScrollImg{
    CGFloat imgWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat imgHeight = 150.0;
    for (int i = 0; i < 3; i++) {
        UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(i*imgWidth, 0, imgWidth, imgHeight)];
//        NSString *imgName = [NSString stringWithFormat:@"shou'ye_0%d",i+1];
        NSString *imgName = [NSString stringWithFormat:@"首页图%d.jpg",i];
        imgView.image = [UIImage imageNamed:imgName];
        [self.scrollView addSubview:imgView];
    }
    self.scrollView.contentSize = CGSizeMake(3*imgWidth, 0);
}

#pragma mark - UITableViewDataSource -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.curStates.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SPStateCell *cell = [SPStateCell cellWithTableView:tableView];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.states[indexPath.row];
    cell.commentBtn.tag = indexPath.row;
    [cell.commentBtn addTarget:self action:@selector(toState:) forControlEvents:UIControlEventTouchUpInside];
    cell.headImg.userInteractionEnabled = YES;
    cell.headImg.tag = [cell.model.ID integerValue];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(headImgClick:)];
    [cell.headImg addGestureRecognizer:tap];
    return cell;
}
- (void)headImgClick:(UITapGestureRecognizer *)tap{
    NSInteger tag = tap.view.tag;
    SPUserInfoController *userInfoVC = [[UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:NSStringFromClass([SPUserInfoController class])];
    userInfoVC.index = [NSNumber numberWithInteger:tag];
    [self.navigationController pushViewController:userInfoVC animated:YES];
}
- (void)toState:(UIButton *)button{
    SPStateViewController *stateVC = [[UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:NSStringFromClass([SPStateViewController class])];
    NSInteger index = button.tag;
    stateVC.stateModel = self.states[index];
    [self.navigationController pushViewController:stateVC animated:YES];
}
#pragma mark - UITableViewDelegate -
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SPStateViewController *stateVC = [[UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:NSStringFromClass([SPStateViewController class])];
    stateVC.stateModel = self.states[indexPath.row];
    [self.navigationController pushViewController:stateVC animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SPHomeStateModel *model = self.states[indexPath.row];
    return model.cellHeight;
}
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
//    return 10.0f;
//}

#pragma mark - UIScrollViewDelegate -
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offsetX = self.scrollView.contentOffset.x;
    int pageNumber = (offsetX + scrollView.frame.size.width*0.5)/scrollView.frame.size.width;
    self.pageControl.currentPage = pageNumber;
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    //销毁计时器
    [self.timer invalidate];
    self.timer = nil;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self addTimer];
}
#pragma mark - 添加计时器 -
- (void)addTimer{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(changeImg) userInfo:nil repeats:YES];
    //获取当前循环对象
    NSRunLoop *runloop = [NSRunLoop currentRunLoop];
    //改变self.Timer的优先级
    [runloop addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)changeImg{
    NSInteger page = self.pageControl.currentPage;
    if (page == self.pageControl.numberOfPages-1) {
        page = 0;
    }else{
        page++;
    }
    CGFloat offsetX = self.scrollView.frame.size.width*page;
    [self.scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *location = locations.lastObject;
    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        UIButton *cityBtn = self.navigationItem.leftBarButtonItem.customView;
        self.navigationItem.leftBarButtonItem.customView.tintColor = [UIColor yellowColor];
        if (!error) {
            CLPlacemark *placemark = placemarks.firstObject;
            self.locationCity = placemark.locality;
            [cityBtn setTitle:self.locationCity forState:UIControlStateNormal];
            [cityBtn.titleLabel setTextColor:[UIColor yellowColor]];
            NSLog(@"%@",self.locationCity);
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault setObject:self.locationCity forKey:@"locationCity"];
//            self.navigationItem.leftBarButtonItem.title = self.locationCity;
        }else{
            [cityBtn setTitle:@"定位失败" forState:UIControlStateNormal];
            [cityBtn sizeToFit];
//           ® [self.view layoutIfNeeded];
            [cityBtn.titleLabel setTextColor:[UIColor yellowColor]];
            NSLog(@"定位失败ERROR:%@",error);
        }
    }];
    [manager stopUpdatingLocation];
}

- (void)cityViewController:(SPCityViewController *)cityViewController didSelectedCity:(NSString *)city{
    if (city.length > 3) {
        city = [city substringToIndex:3];
    }
    self.selectdCity = city;
    UIButton *cityBtn = self.navigationItem.leftBarButtonItem.customView;
    [cityBtn setTitle:city forState:UIControlStateNormal];
    NSLog(@"%@",city);
}
@end
